package com.campus.client.view;

import com.campus.common.vo.User;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class AdminCourseFrame {

    private Button btnLogout;
    private User user = new User();
    public User getUser() { return user; }
    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) {
        // 主布局
        BorderPane root = new BorderPane();

        // 校徽和标题
        ImageView logoView = new ImageView(new Image(getClass().getResource("/badge.png").toExternalForm()));
        logoView.setFitHeight(40);
        logoView.setPreserveRatio(true);

        Label lblTitleCN = new Label("选课");
        lblTitleCN.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-font-weight: bold;");
        Label lblTitleEN = new Label("Course Selection");
        lblTitleEN.setStyle("-fx-text-fill: white; -fx-font-size: 12px;");

        VBox titleBox = new VBox(2, lblTitleCN, lblTitleEN);
        titleBox.setAlignment(Pos.CENTER_LEFT);
        HBox logoAndTitle = new HBox(8, logoView, titleBox);

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        Label lblRole = new Label("当前身份：管理员");
        lblRole.setStyle("-fx-text-fill: white; -fx-font-size: 12px; -fx-font-weight: bold;");

        Image logoutImg = new Image(getClass().getResource("/logout.png").toExternalForm());
        ImageView logoutIcon = new ImageView(logoutImg);
        logoutIcon.setFitHeight(14);
        logoutIcon.setPreserveRatio(true);

        btnLogout = new Button("退出选课", logoutIcon);
        btnLogout.getStyleClass().add("logout-button");
        btnLogout.setOnAction(e -> {
            try { back(); }
            catch (IOException ex) { throw new RuntimeException(ex); }
        });

        HBox topBar = new HBox(15, logoAndTitle, spacer, lblRole, btnLogout);
        topBar.setPadding(new Insets(6));
        topBar.setStyle("-fx-background-color: #3b7bc3;");
        root.setTop(topBar);

        // 左侧侧边栏
        VBox sidebar = new VBox(0);
        sidebar.setPadding(new Insets(15, 0, 15, 0));
        sidebar.setStyle("-fx-background-color: #3b7bc3");

        SidebarButton btnAllCourses = new SidebarButton("所有课程");
        SidebarButton btnAddCourse = new SidebarButton("添加课程");
        SidebarButton btnDeleteCourse = new SidebarButton("删除课程");

        List<SidebarButton> sidebarButtons = Arrays.asList(btnAllCourses, btnAddCourse, btnDeleteCourse);
        for (SidebarButton btn : sidebarButtons) {
            btn.setPrefHeight(50);
            btn.setMaxWidth(Double.MAX_VALUE);
        }

        sidebar.getChildren().addAll(sidebarButtons);
        root.setLeft(sidebar);

        // 中间内容区域
        BorderPane contentArea = new BorderPane();

        // 顶部搜索栏
        HBox searchBar = new HBox(10);
        searchBar.setPadding(new Insets(10));
        searchBar.setAlignment(Pos.CENTER_LEFT);

        TextField searchField = new TextField();
        searchField.setPromptText("输入课程编号和名称");
        searchField.setPrefWidth(300);

        Button searchBtn = new Button("🔍 查询");
        searchBtn.setStyle("-fx-background-color: #3b7bc3; -fx-text-fill: white; -fx-font-weight: bold;");
        searchBtn.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            try {
                if (keyword.isEmpty()) {
                    AdminCourseView cv = new AdminCourseView(AdminCourseView.CourseViewMode.ALL);
                    contentArea.setCenter(cv.getView());
                    updateSidebarSelection(sidebarButtons, btnAllCourses);
                } else {
                    AdminCourseView cv = new AdminCourseView(AdminCourseView.CourseViewMode.QUERY, keyword);
                    contentArea.setCenter(cv.getView());
                    updateSidebarSelection(sidebarButtons, null); // 查询时不高亮任何按钮
                }
            } catch (IOException ex) {
                showError("加载课程失败", "无法连接到服务器，请检查网络或服务器状态！");
            }
        });

        searchBar.getChildren().addAll(searchField, searchBtn);
        contentArea.setTop(searchBar);

        try {
            AdminCourseView defaultView = new AdminCourseView(AdminCourseView.CourseViewMode.ALL);
            contentArea.setCenter(defaultView.getView());
            updateSidebarSelection(sidebarButtons, btnAllCourses);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 点击事件
        btnAllCourses.setOnAction(e -> {
            try {
                AdminCourseView cv = new AdminCourseView(AdminCourseView.CourseViewMode.ALL);
                contentArea.setCenter(cv.getView());
                updateSidebarSelection(sidebarButtons, btnAllCourses);
            } catch (IOException ex) {
                showError("查询课程失败", "无法连接到服务器，请检查网络或服务器状态！");
            }
        });

        btnAddCourse.setOnAction(e -> {
            try {
                AdminCourseView cv = new AdminCourseView(AdminCourseView.CourseViewMode.ADD);
                contentArea.setCenter(cv.getView());
                updateSidebarSelection(sidebarButtons, btnAddCourse);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
        btnDeleteCourse.setOnAction(e -> {
            try
            {
                AdminCourseView cv = new AdminCourseView(AdminCourseView.CourseViewMode.DELETE); // ✅ 用 DELETE 模式
                contentArea.setCenter(cv.getView());
                updateSidebarSelection(sidebarButtons, btnDeleteCourse);
            }
            catch
            (IOException ex) {
                ex.printStackTrace();
            }
        });

        root.setCenter(contentArea);

        // 场景
        Scene scene = new Scene(root, 1000, 700);
        scene.getStylesheets().add(getClass().getResource("/CourseView.css").toExternalForm());

        primaryStage.setTitle("管理员端课程管理系统");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void back() throws IOException {
        Stage adminCourseStage = (Stage) btnLogout.getScene().getWindow();
        AdminMainFrame adminMainFrame = new AdminMainFrame();
        adminMainFrame.setUser(user.getId(), user.getPassword(), user.getRole());
        Stage stage = new Stage();
        adminMainFrame.show(stage);
        adminCourseStage.close();
    }

    private void updateSidebarSelection(List<SidebarButton> buttons, SidebarButton selected) {
        for (SidebarButton btn : buttons) {
            btn.setSelected(false);
        }
        if (selected != null) selected.setSelected(true);
    }

    private void showError(String header, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
}
